package com.earthchen.mattress.dao;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.earthchen.mattress.config.DBPoolConnection;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 数据库工具类
 *
 * @author: EarthChen
 * @date: 2018/04/27
 */
public class DBHelper {

    public PreparedStatement pst = null;

    private DruidPooledConnection connection = null;

    public DBHelper(String sql) {
        DBPoolConnection dbp = DBPoolConnection.getInstance();

        try {
            connection = dbp.getConnection();
            connection.setAutoCommit(true);
            //准备执行语句
            pst = connection.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 回收资源关闭连接
     */
    public void close() {
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException e) {
                System.out.println("pst关闭失败");
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                System.out.println("数据库链接关闭失败");
            }
        }
    }
}
